// Copyright 2020 morgine.com. All rights reserved.

package cros

import "net/http"

// ANY 方法是自定义方法, 用于匹配所有方法, 为了方便文档测试, 所以必须要有一个具体的方法
var DefaultCrossSiteMethods = []string{"GET", "POST", "PUT", "DELETE", "ANY"}

var DefaultCrossSiteHeaders = []string{"Content-Type", "Authorization"}

var DefaultCrossSiteOrigin = "*"

// 添加默认的跨域访问响应头信息
func AddDefaultCrossSiteAccess(header http.Header) {
	AllowCrossSiteOrigin(header, DefaultCrossSiteOrigin)
	AllowCrossSiteHeaders(header, DefaultCrossSiteHeaders)
	AllowCrossSiteMethods(header, DefaultCrossSiteMethods)
}

var headerKeyAccessHeaders = "Access-Control-Allow-Headers"
var headerKeyAccessMethods = "Access-Control-Allow-Methods"
var headerKeyAccessOrigin = "Access-Control-Allow-Origin"

var headerKeyAccessCredentials = "Access-Control-Allow-Credentials"

var exposeHeaders = "Access-Control-Expose-Headers"

// 允许跨域请求头
func AllowCrossSiteHeaders(header http.Header, headers []string) {
	header[headerKeyAccessHeaders] = append(header[headerKeyAccessHeaders], headers...)
}

// 允许跨域请求方法
func AllowCrossSiteMethods(header http.Header, methods []string) {
	header[headerKeyAccessMethods] = append(header[headerKeyAccessMethods], methods...)
}

// 允许跨域请求站点
func AllowCrossSiteOrigin(header http.Header, origin string) {
	header[headerKeyAccessOrigin] = append(header[headerKeyAccessOrigin], origin)
}

// 允许跨域 cookies, 如果开启, 则 Access-Control-Allow-Origin 响应头必须为具体网站地址, 不可为 *
func AllowCrossSiteCredentials(header http.Header) {
	header.Set(headerKeyAccessCredentials, "true")
}

// 允许浏览器操作的响应头
func ExposeCrossSiteHeaders(header http.Header, headers []string) {
	header[exposeHeaders] = append(header[exposeHeaders], headers...)
}
